<template>
  <div class="sensitive-word-management">
    <div class="header">
      <h2>敏感词管理</h2>
      <div class="actions">
        <el-button type="primary" @click="showAddDialog">添加敏感词</el-button>
        <el-button type="success" @click="showBatchAddDialog">批量添加</el-button>
      </div>
    </div>

    <div class="search-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索敏感词"
        clearable
        @keyup.enter="handleSearch"
        style="width: 300px; margin-right: 10px;"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
    </div>

    <el-table :data="sensitiveWords" v-loading="loading" stripe>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="word" label="敏感词" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.per_page"
        :page-sizes="[20, 50, 100, 200]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加敏感词对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加敏感词" width="400px">
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="80px">
        <el-form-item label="敏感词" prop="word">
          <el-input v-model="addForm.word" placeholder="请输入敏感词" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAdd" :loading="addLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑敏感词对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑敏感词" width="400px">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="80px">
        <el-form-item label="敏感词" prop="word">
          <el-input v-model="editForm.word" placeholder="请输入敏感词" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdate" :loading="editLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量添加敏感词对话框 -->
    <el-dialog v-model="batchAddDialogVisible" title="批量添加敏感词" width="600px">
      <el-form :model="batchAddForm" :rules="batchAddRules" ref="batchAddFormRef" label-width="100px">
        <el-form-item label="敏感词列表" prop="words">
          <el-input
            v-model="batchAddForm.words"
            type="textarea"
            :rows="10"
            placeholder="请输入敏感词，每行一个"
          />
          <div class="form-tip">每行输入一个敏感词，系统会自动去重</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchAddDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBatchAdd" :loading="batchAddLoading">批量添加</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { admin } from '@/api'

const loading = ref(false)
const sensitiveWords = ref([])
const searchKeyword = ref('')

const pagination = reactive({
  page: 1,
  per_page: 20,
  total: 0,
  pages: 0,
  has_prev: false,
  has_next: false
})

// 添加敏感词
const addDialogVisible = ref(false)
const addLoading = ref(false)
const addFormRef = ref(null)
const addForm = reactive({
  word: ''
})
const addRules = {
  word: [
    { required: true, message: '请输入敏感词', trigger: 'blur' },
    { min: 1, max: 100, message: '敏感词长度在1到100个字符', trigger: 'blur' }
  ]
}

// 编辑敏感词
const editDialogVisible = ref(false)
const editLoading = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  id: null,
  word: ''
})
const editRules = {
  word: [
    { required: true, message: '请输入敏感词', trigger: 'blur' },
    { min: 1, max: 100, message: '敏感词长度在1到100个字符', trigger: 'blur' }
  ]
}

// 批量添加敏感词
const batchAddDialogVisible = ref(false)
const batchAddLoading = ref(false)
const batchAddFormRef = ref(null)
const batchAddForm = reactive({
  words: ''
})
const batchAddRules = {
  words: [
    { required: true, message: '请输入敏感词列表', trigger: 'blur' }
  ]
}

const fetchSensitiveWords = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      per_page: pagination.per_page,
      search: searchKeyword.value
    }
    
    const response = await admin.getSensitiveWords(params)
    sensitiveWords.value = response.data.sensitive_words
    Object.assign(pagination, response.data.pagination)
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '获取敏感词列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  fetchSensitiveWords()
}

const handleSizeChange = (val) => {
  pagination.per_page = val
  pagination.page = 1
  fetchSensitiveWords()
}

const handleCurrentChange = (val) => {
  pagination.page = val
  fetchSensitiveWords()
}

const showAddDialog = () => {
  addForm.word = ''
  addDialogVisible.value = true
}

const handleAdd = async () => {
  addFormRef.value.validate(async (valid) => {
    if (valid) {
      addLoading.value = true
      try {
        await admin.addSensitiveWord({ word: addForm.word })
        ElMessage.success('敏感词添加成功')
        addDialogVisible.value = false
        fetchSensitiveWords()
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '添加敏感词失败')
      } finally {
        addLoading.value = false
      }
    }
  })
}

const handleEdit = (row) => {
  editForm.id = row.id
  editForm.word = row.word
  editDialogVisible.value = true
}

const handleUpdate = async () => {
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      editLoading.value = true
      try {
        await admin.updateSensitiveWord(editForm.id, { word: editForm.word })
        ElMessage.success('敏感词更新成功')
        editDialogVisible.value = false
        fetchSensitiveWords()
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '更新敏感词失败')
      } finally {
        editLoading.value = false
      }
    }
  })
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除敏感词 "${row.word}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await admin.deleteSensitiveWord(row.id)
    ElMessage.success('敏感词删除成功')
    fetchSensitiveWords()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '删除敏感词失败')
    }
  }
}

const showBatchAddDialog = () => {
  batchAddForm.words = ''
  batchAddDialogVisible.value = true
}

const handleBatchAdd = async () => {
  batchAddFormRef.value.validate(async (valid) => {
    if (valid) {
      batchAddLoading.value = true
      try {
        const words = batchAddForm.words
          .split('\n')
          .map(word => word.trim())
          .filter(word => word.length > 0)
        
        if (words.length === 0) {
          ElMessage.error('请输入至少一个敏感词')
          return
        }
        
        const response = await admin.batchAddSensitiveWords({ words })
        const result = response.data
        
        let message = `成功添加 ${result.added_count} 个敏感词`
        if (result.duplicate_count > 0) {
          message += `，跳过 ${result.duplicate_count} 个重复词`
        }
        
        ElMessage.success(message)
        batchAddDialogVisible.value = false
        fetchSensitiveWords()
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '批量添加敏感词失败')
      } finally {
        batchAddLoading.value = false
      }
    }
  })
}

onMounted(() => {
  fetchSensitiveWords()
})
</script>

<style scoped>
.sensitive-word-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>